package com.frinder.base.strategy;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

import static com.frinder.base.strategy.StrategyCounter.getAndIncrement;
import static com.frinder.base.strategy.StrategyCounter.getValue;

/**
 * @ClassName BaseStrategy
 * @Description 策略基类
 * @Author frinder
 * @Date 2019/9/10 17:55
 * @Verion 1.0
 */
@Slf4j
public class BaseStrategy<T> implements IStrategy<T> {

    /**
     * 策略链
     */
    private final List<IStrategy> strategies = Lists.newArrayList();

    /**
     * 注册策略
     *
     * @param strategy
     */
    public BaseStrategy register(IStrategy strategy) {
        strategies.add(strategy);
        return this;
    }

    /**
     * 策略链调用
     *
     * @param payload
     */
    @Override
    public void handle(T payload) {
        if (getValue() >= strategies.size()) {
            log.warn("无匹配的处理策略，请检查！请求：{}", payload);
            return;
        }
        // 获取策略后索引++
        IStrategy currStrategy = strategies.get(getAndIncrement());
        // 策略处理
        currStrategy.handle(payload);
    }

}
